package cn.bopomo.dealer.wow.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

import cn.bopomo.dealer.base.util.Page;
import cn.bopomo.dealer.base.util.SecurityUtil;
import cn.bopomo.dealer.wow.service.IYouyiService;
import cn.bopomo.dealer.wow.vo.Wow711CardObject;

import com.metaparadigm.jsonrpc.JSONSerializer;

public class YouyiServiceImpl implements IYouyiService {
	
	private String url = "http://www.wow711.com/selcard.php";
	
	public Wow711CardObject getCardUsedInfo(String cardNo) {
		// TODO Auto-generated method stub
		Wow711CardObject cardObject = null;
		HttpClient client = new HttpClient();
		int type = 1;
		String params = "?act=" + type + "&num=" + cardNo + "&key=" + this.genPrivateKey(cardNo,type);
		GetMethod getMethod = new GetMethod(url + params);
		String result = null;
		try {
			int _result = client.executeMethod(getMethod);
			if (_result == 200)
				result = new BufferedReader(new InputStreamReader(getMethod
                        .getResponseBodyAsStream())).readLine().trim();
				if (result != null){
					cardObject = this.convertToCardObj(result);
				}
            else {
                //log.info("远程调用返回：" + _result);
            }

		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return cardObject;
	}

	public List getCardUsedInfos(String startDate, String endDate, Wow711CardObject conditionObj) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date _startDate = null;
		Date _endDate = null;
		String default_fee_reg = "(\\d){1,3}\\.(\\d){2}";
		String default_type_reg = "(gold|ub)";
		if (conditionObj != null){
			if (conditionObj.getUseFor() != null)
				default_type_reg = conditionObj.getUseFor();
			if (conditionObj.getCardValue() != null)
				default_fee_reg = conditionObj.getCardValue(); 
		}
		try {
			_startDate = sdf.parse(startDate);
			_endDate = sdf.parse(endDate);
			
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (_startDate == null || _endDate == null){
			return null;
		}
		
		if (_startDate.after(_endDate))
			return null;
		
		List cardList = new ArrayList();
		HttpClient client = new HttpClient();
		int type = 2;
		String content = sdf.format(_startDate) + "-" + sdf.format(_endDate);
		String params = "?act=" + type + "&st=" + sdf.format(_startDate) + "&et=" + sdf.format(_endDate) + "&key=" + this.genPrivateKey(content,type);
		GetMethod getMethod = new GetMethod(url + params);
		String result = null;
		//正则表达式
		String regLine = "^card=(\\d){15},usedip=(\\d){1,3}\\.(\\d){1,3}\\.(\\d){1,3}\\.(\\d){1,3},usedtime=(\\d){4}-(\\d){1,2}-(\\d){1,2}\\s((0?[0-9])|(1[0-9])|2[0-3])\\:([0-5]?[0-9])\\:([0-5]?[0-9]),card_value=" + default_fee_reg + ",usefor=" + default_type_reg +"$";
		try {
			int _result = client.executeMethod(getMethod);
			if (_result == 200){
				BufferedReader br = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));
				Pattern pattern= Pattern.compile(regLine);
				
				while((result = br.readLine()) != null){
					Matcher m=pattern.matcher(result);
					if (m.find()){
						Wow711CardObject cardObject = cardObject = this.convertToCardObj(result);  
						cardList.add(cardObject);
					}
				}	
					
					
			}else {
                //log.info("远程调用返回：" + _result);
            }

		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return cardList;
	}

	
	private String genPrivateKey(String content, int type){
		String result = null;
		String key = "w7o1w1";
		result = SecurityUtil.MD5(key + "-" + type + "-" + content);
		/*
		switch (type){
		case 1:
			result = SecurityUtil.MD5(key + "-" + type + "-" + content);
			break;
		case 2:
			result = SecurityUtil.MD5(key + "-" + type + "-" + content);
			break;
		default:
		}
		*/
		return result;
	}
	
	private Wow711CardObject convertToCardObj(String readLine){
		Wow711CardObject resultObj = new Wow711CardObject();
		String[] str_array = readLine.split(",");
		for (int i = 0;i<str_array.length;i++){
			String[] nameValue = str_array[i].split("=");
			if (nameValue.length <=1){
				resultObj.setError(str_array[i]);
				continue;
			}
			this.setObjectValue(resultObj,nameValue);
		}
		
		return resultObj;
	}
	
	private void setObjectValue(Wow711CardObject objCard, String[] nameValue){
		String name = nameValue[0];
		String value = nameValue[1];
		if ("card".equalsIgnoreCase(name)){
			objCard.setCardNo(value);
			return;
		}
		
		if ("used".equalsIgnoreCase(name)){
			if ("1".equals(value)){
				objCard.setUsed(true);
			}
			return;
		}
		
		if ("isexpiry".equalsIgnoreCase(name)){
			if ("1".equals(value)){
				objCard.setExpiry(true);
			}
			return;
		}
		
		if ("card_value".equalsIgnoreCase(name)){
			if (value != null && !"".equals(value)){
				objCard.setCardValue(value);
			}
			return;
		}
		
		if ("usefor".equalsIgnoreCase(name)){
			if ("ub".equalsIgnoreCase(value)){
				objCard.setUseFor("优币");
			}else if ("gold".equalsIgnoreCase(value)){
				objCard.setUseFor("魔兽金币");
			}
			return;
		}
		
		if ("usedip".equalsIgnoreCase(name)){
			objCard.setUseIp(value);
			return;
		}
		if ("usedtime".equalsIgnoreCase(name)){
			objCard.setUsedTime(value);
			return;
		}
		
	}
	
	public List toPageList(List wow711CardList, int pageSize, Page pageObj){
		if (pageSize > pageObj.getMaxPage())
			return null;
		List resultList = null;
		if (pageSize == pageObj.getMaxPage()){
			int contentSize = pageObj.getMaxRowCount() % pageObj.getRowsPerPage();
			
			if (contentSize == 0){
				contentSize = pageObj.getRowsPerPage();
			}
			resultList = new ArrayList(contentSize);
			/*
			for (int i = 0; i < contentSize;i ++){
				resultList.add(wow711CardList.get(i));
			}
			*/
			for (int i = wow711CardList.size() - contentSize;i<wow711CardList.size();i++){
				resultList.add(wow711CardList.get(i));
			}
			
		}else{
			//int startIndex = wow711CardList.size() - pageSize * pageObj.getRowsPerPage();
			int startIndex = (pageSize - 1) * pageObj.getRowsPerPage();
			resultList = new ArrayList(pageObj.getRowsPerPage());
			for (int i = startIndex;i < (startIndex + pageObj.getRowsPerPage());i++){
				resultList.add(wow711CardList.get(i));
			}
		}
		
		return resultList;
	}
	

	public DefaultPieDataset getPieChartDataSet(List wow711CardList) {
		DefaultPieDataset dataset = new DefaultPieDataset();    
		Map priceType = new HashMap();
		for (int i = 0; i< wow711CardList.size();i++){
			Wow711CardObject tmpCard = (Wow711CardObject)wow711CardList.get(i);
			if (priceType.containsKey(tmpCard.getCardValue())){
				Integer tmpInt = (Integer)priceType.get(tmpCard.getCardValue());
				tmpInt = new Integer(tmpInt.intValue() + 1);
				priceType.put(tmpCard.getCardValue(),tmpInt);
			}else{
				priceType.put(tmpCard.getCardValue(),new Integer(1));
			}
		}
		Iterator it = priceType.entrySet().iterator();
		
		while(it.hasNext()){ 
			Entry en=(Entry )it.next(); 
			dataset.setValue((String)en.getKey() + "元", ((Integer)en.getValue()).doubleValue()); 
		} 

		
		// TODO Auto-generated method stub
		return dataset;
	}
	
	public static void main(String[] s){
		String default_fee_reg = "(\\d){1,3}\\.(\\d){2}";
		String default_type_reg = "(gold|ub)";
		
		String a = "^card=(\\d){15},usedip=(\\d){1,3}\\.(\\d){1,3}\\.(\\d){1,3}\\.(\\d){1,3},usedtime=(\\d){4}-(\\d){1,2}-(\\d){1,2}\\s((0?[0-9])|(1[0-9])|2[0-3])\\:([0-5]?[0-9])\\:([0-5]?[0-9]),card_value=" + default_fee_reg + ",usefor=" + default_type_reg +"$";
		Pattern pattern= Pattern.compile(a);
		String value = "card=100282607233182,usedip=121.9.242.175,usedtime=2008-02-29 23:43:24,card_value=3.00,usefor=ub";
		Matcher m=pattern.matcher(value); 
		System.out.println(m.find());
	}
}
